package com.kaifamiao.controller;

import com.kaifamiao.entity.User;
import com.kaifamiao.enums.UserType;
import com.kaifamiao.exception.ServiceException;
import com.kaifamiao.service.TokenService;
import com.kaifamiao.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;

    private final Map<String, String> types = Map.of("tel", "手机号", "email", "邮箱", "account", "账号");

    @PostMapping("/register/{type}")
    public Map<String,Object> register(@RequestBody User user, @PathVariable("type") String type) {
        log.info( "用户注册" );
        Map<String, Object> result = userService.exists(user, UserType.valueOf(type.toUpperCase()));
        boolean exists = (Boolean) result.get( "exists" );
        if( exists ) {
            return Map.of("success", false, "message", result.get("message") );
        }
        try {
            if (userService.save(user)) {
                return Map.of("success", true, "message", "注册成功");
            }
            return Map.of("success", false, "message", "注册失败");
        } catch ( ServiceException e ) {
            log.error( "保存用户时发生故障", e);
            return Map.of("success", false, "message", "注册失败", "reason", e.getMessage() );
        }
    }

    @PostMapping("/login/{type}")
    public Map<String,Object> login(@RequestBody User user, @PathVariable("type") String type) {
        log.info("用户登录");
        User u = userService.find(user, UserType.valueOf(type.toUpperCase()));
        if( u == null ) {
            return Map.of("success", false, "message", types.get(type) + "在系统中不存在");
        }
        // 用数据库中存储的盐值对用户在页面上输入的密码进行加密
        String encrypted = userService.encrypt(user.getPassword(), u.getSalt());
        // 再跟数据库中存储的用户密码比较
        if( !encrypted.equals( u.getPassword() ) ) {
            return Map.of("success", false, "message", "密码错误");
        }

        Map<String,Object> map = new HashMap<>();
        map.put("id", u.getId());
        map.put("tel", u.getTel());
        map.put("email", u.getEmail());
        map.put("account", u.getAccount());
        map.put("nickname", u.getNickname());
        // 以 map 中的键值对为载荷(payload)创建 JSON Web Token
        String token = tokenService.generate(map);

        return Map.of("success", true, "message", "登录成功", "token", token );
    }

}
